home *** CD-ROM | disk | FTP | other *** search
- Path: ghost.cbm.com!usenet
- From: Dave Payne <paynedc@cbm.com>
- Newsgroups: comp.lang.c
- Subject: Determining the length of an int in string form
- Date: Wed, 13 Mar 1996 08:40:40 -0500
- Organization: CBM Technologies, INC
- Message-ID: <3146D058.DD7@cbm.com>
- NNTP-Posting-Host: cujo.cbm.com
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 2.0 (Win16; I)
-
- Consider this:
-
- I have a variable of type int, and I would like to use the sprintf()
- function to write this variable to a string. However, I want to
- dynamically allocate the space for the string, and only malloc enough
- space to hold the int. Here's a code fragment that may illustrate this
- more clearly:
-
- void func1() {
-
- int i = 1234;
- char *a;
-
- /*
- * We need to malloc enough space to hold "The value of i is"
- * AND 1234. The 4 + 1 is for the 4 bytes that 1234 will occupy
- * in the string, and for a NULL terminator.
- */
- a = malloc(strlen("The value of i is ") + 4 + 1);
-
- /*
- * Use sprintf() to build the desired string.
- */
-
- sprintf(a,"%s%d","The value of i is ",i);
-
- free(a);
-
- }
-
- In this example, I hardcoded the 4, because I knew that 1234 was 4
- characters long. I would like to be able to determine this at runtime,
- and malloc enough space accordingly. I guess what I need is a type of
- itoa (similar to the atoi() C function) that will convert an integer to
- its ASCII representation. Then I could just do I strlen() on the return
- value of itoa to figure out how many characters the integer will occupy
- in string form.
-
- Does anyone have any suggestions?
-
- Much appreciated,
- - Dave Payne
- Atkins, VA
-